//
//  HomeViewController.m
//  Conva
//
//  Created by cruise on 2017/12/26.
//  Copyright © 2017年 com.conva. All rights reserved.
//

#import "CAHomeViewController.h"
#import "SDCycleScrollView.h"
#import "CACategoryView.h"
#import "CASaleTableViewCell.h"

#import "CACategoryTableViewCell.h"
#import "CAGoodsView.h"
#import "CAVipView.h"
#import "CAGoodsListViewController.h"

#import "CABannerApi.h"
#import "CACategoryApi.h"
#import "UIImageView+WebCache.h"

#import "CACategoryViewController.h"
#import "CAOrderDoneViewController.h"
#import "CAUpgradeViewController.h"

@interface CAHomeViewController ()<SDCycleScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) NSArray *saleArray;
@property (nonatomic, strong) NSArray *categoryArray;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *containterView;
@property (nonatomic, strong) SDCycleScrollView *sdScrollView;
@property (nonatomic, strong) CACategoryView *categoryView;

@property (nonatomic, strong) UITableView *saleTableView;

@property (nonatomic, strong) UILabel *cateTitleLabel;
@property (nonatomic, strong) UITableView *cateTableView;
@property (nonatomic, strong) CAGoodsView *goodsView;
@property (nonatomic, strong) CAVipView *vipView;
@property (nonatomic, strong) UIImageView *upgradeImageView;

@end

static NSString *saleIdentifier = @"sale";
static NSString *cateIdentifier = @"category";

@implementation CAHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES; 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (GVUD.token == nil) {
        GVUD.token = @"";
    }
    [self loadBanner];
    [self loadCategory];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
#endif
}

- (void)lm_initialDefaultsForController
{
//    NSArray *imagesURLStrings = @[
//                                  @"https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a4b3d7085dee3d6d2293d48b252b5910/0e2442a7d933c89524cd5cd4d51373f0830200ea.jpg",
//                                  @"https://ss0.baidu.com/-Po3dSag_xI4khGko9WTAnF6hhy/super/whfpf%3D425%2C260%2C50/sign=a41eb338dd33c895a62bcb3bb72e47c2/5fdf8db1cb134954a2192ccb524e9258d1094a1e.jpg",
//                                  @"http://c.hiphotos.baidu.com/image/w%3D400/sign=c2318ff84334970a4773112fa5c8d1c0/b7fd5266d0160924c1fae5ccd60735fae7cd340d.jpg"
//                                  ];
//    self.imageArray = imagesURLStrings;
//
//    NSArray *saleArray = @[
//                           @{@"image" : @"sale1"},
//                           @{@"image" : @"sale2"},
//                           @{@"image" : @"sale3"},
//                           @{@"image" : @"sale4"},
//                           @{@"image" : @"sale5"},
//                           ];
//    _saleArray = saleArray;
//
//    NSArray *cateArray = @[
//                           @{@"image" : @"cate1"},
//                           @{@"image" : @"cate2"},
//                           @{@"image" : @"cate3"},
//                           @{@"image" : @"cate4"},
//                           ];
//    _categoryArray = cateArray;
}

- (void)lm_configNavigationForController
{
    self.navigationItem.title = @"靓女汇商城";
    self.navigationController.navigationBar.barTintColor = RGBCOLOR(241, 90, 36);
    self.navigationController.navigationBar.tintColor = RGBCOLOR(241, 90, 36);
    self.navigationController.navigationBar.backgroundColor = RGBCOLOR(241, 90, 36);
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor], NSFontAttributeName : [UIFont systemFontOfSize:16]};
    
    //    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    //    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
}

- (void)lm_createViewForController
{
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.containterView];
    
    [self.containterView addSubview:self.sdScrollView];
    
    [self.containterView addSubview:self.categoryView];
    
    [self.containterView addSubview:self.saleTableView];
    
    [self.containterView addSubview:self.cateTitleLabel];
    [self.containterView addSubview:self.cateTableView];
    [self.containterView addSubview:self.goodsView];
    [self.containterView addSubview:self.vipView];
    
    [self.containterView addSubview:self.upgradeImageView];
    
    [self.view setNeedsUpdateConstraints];
}

-(void)lm_bindViewModelForController
{
    
}

#pragma mark - Layout

- (void)updateViewConstraints
{
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [_containterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [_sdScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.containterView);
        make.height.mas_equalTo(200);
    }];
    
    [_categoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.sdScrollView.mas_bottom);
        make.height.mas_equalTo(60);
    }];
    
    [_saleTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.categoryView.mas_bottom);
        make.height.mas_offset(200 * _saleArray.count);
    }];
    
    [_cateTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.saleTableView.mas_bottom);
        make.height.mas_equalTo(50);
    }];
    
    [_cateTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.cateTitleLabel.mas_bottom);
        make.height.mas_offset(150 * _categoryArray.count);
    }];
    
    [_goodsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.cateTableView.mas_bottom);
        make.height.mas_equalTo(410);
    }];
    
    [_vipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.top.equalTo(self.goodsView.mas_bottom);
        make.height.mas_equalTo(410);
    }];
    
    [_upgradeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.containterView);
        make.top.equalTo(self.vipView.mas_bottom);
        make.height.mas_equalTo(220);
    }];
    
    [_containterView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.upgradeImageView.mas_bottom).offset(50);
    }];
    
    [super updateViewConstraints];
}

#pragma mark - Getter
- (UIScrollView *) scrollView {
    if (!_scrollView) {
        _scrollView = [UIScrollView new];
        _scrollView.backgroundColor = [UIColor whiteColor];
    }
    return _scrollView;
}

- (UIView *) containterView {
    if (!_containterView) {
        _containterView = [UIView new];
        _containterView.backgroundColor = [UIColor clearColor];
    }
    return _containterView;
}

- (SDCycleScrollView *) sdScrollView {
    if (!_sdScrollView) {
        _sdScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero shouldInfiniteLoop:YES imageNamesGroup:self.imageArray];
        _sdScrollView.delegate = self;
        _sdScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
//        [demoContainerView addSubview:cycleScrollView];
        _sdScrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return _sdScrollView;
}

- (CACategoryView *) categoryView {
    if (!_categoryView) {
        _categoryView = [CACategoryView new];
        
        [[_categoryView.firstButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CAGoodsListViewController *goodsListVC = [CAGoodsListViewController new];
            goodsListVC.vcTitle = @"优品汇专区";
            goodsListVC.isYPH = @"1";
            goodsListVC.isVip = @"0";
            goodsListVC.isSecond = @"0";
            goodsListVC.goodsName = @"";
            goodsListVC.category = @"";
            [self.navigationController pushViewController:goodsListVC animated:YES];
        }];
        
        [[_categoryView.secondButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CAGoodsListViewController *goodsListVC = [CAGoodsListViewController new];
            goodsListVC.vcTitle = @"VIP专区";
            goodsListVC.isYPH = @"0";
            goodsListVC.isVip = @"1";
            goodsListVC.isSecond = @"0";
            goodsListVC.goodsName = @"";
            goodsListVC.category = @"";
            goodsListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:goodsListVC animated:YES];
        }];
        
        [[_categoryView.thirdButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CACategoryViewController *categoryVC =[CACategoryViewController new];
            categoryVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:categoryVC animated:YES];
        }];
        
    }
    return _categoryView;
}

- (UITableView *) saleTableView{
    if (!_saleTableView) {
        _saleTableView = [UITableView new];
        _saleTableView.dataSource = self;
        _saleTableView.delegate = self;
        _saleTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_saleTableView registerClass:[CASaleTableViewCell class] forCellReuseIdentifier:saleIdentifier];
        _saleTableView.scrollEnabled = NO;
        _saleTableView.tag = 1;
    }
    return _saleTableView;
}

- (UILabel *) cateTitleLabel {
    if (!_cateTitleLabel) {
        _cateTitleLabel = [UILabel new];
        _cateTitleLabel.textAlignment = NSTextAlignmentCenter;
//        _cateTitleLabel.text = @"分类CATEGORY";
        _cateTitleLabel.font = [UIFont systemFontOfSize:20];
        //设置字间距 NSKernAttributeName:@1.5f
        NSDictionary *dic = @{NSKernAttributeName:@1.0f
                              
                              };
        
        NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@"分类CATEGORY" attributes:dic];
        [_cateTitleLabel setAttributedText:attributedString];
    }
    return _cateTitleLabel;
}

- (UITableView *) cateTableView{
    if (!_cateTableView) {
        _cateTableView = [UITableView new];
        _cateTableView.dataSource = self;
        _cateTableView.delegate = self;
        _cateTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_cateTableView registerClass:[CACategoryTableViewCell class] forCellReuseIdentifier:cateIdentifier];
        _cateTableView.scrollEnabled = NO;
        _cateTableView.tag = 2;
        
    }
    return _cateTableView;
}

- (CAGoodsView *) goodsView {
    if (!_goodsView) {
        _goodsView = [CAGoodsView new];
        [[_goodsView.enterButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CAGoodsListViewController *goodsListVC = [CAGoodsListViewController new];
            goodsListVC.vcTitle = @"优品汇专区";
            goodsListVC.isYPH = @"1";
            goodsListVC.isVip = @"0";
            goodsListVC.isSecond = @"0";
            goodsListVC.goodsName = @"";
            goodsListVC.category = @"";
            goodsListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:goodsListVC animated:YES];
        }];
    }
    return _goodsView;
}

- (CAVipView *) vipView {
    if (!_vipView) {
        _vipView = [CAVipView new];
        [[_vipView.enterButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            CAGoodsListViewController *goodsListVC = [CAGoodsListViewController new];
            goodsListVC.vcTitle = @"VIP专区";
            goodsListVC.isYPH = @"0";
            goodsListVC.isVip = @"1";
            goodsListVC.isSecond = @"0";
            goodsListVC.goodsName = @"";
            goodsListVC.category = @"";
            goodsListVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:goodsListVC animated:YES];
        }];
    }
    return _vipView;
}

- (UIImageView *) upgradeImageView {
    if (!_upgradeImageView) {
        _upgradeImageView = [UIImageView new];
        _upgradeImageView.image = LMImageNamed(@"upgrade");
        _upgradeImageView.contentMode = UIViewContentModeScaleAspectFit;
        
        UITapGestureRecognizer *gesture = [UITapGestureRecognizer new];
        [self.upgradeImageView addGestureRecognizer:gesture];
        [[gesture rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            CAUpgradeViewController *upgradeVC = [CAUpgradeViewController new];
            upgradeVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:upgradeVC animated:YES];
        }];
    }
    return _upgradeImageView;
}

#pragma mark private method
- (void) loadBanner {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    CABannerApi *bannerApi = [[CABannerApi alloc] init];
    [bannerApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        CABannerApi *api = (CABannerApi *) request;
        if (api.done) {
            self.imageArray = api.responseObject[@"result"][@"banner_ad"];
            self.sdScrollView.imageURLStringsGroup = self.imageArray;
            self.saleArray = api.responseObject[@"result"][@"listAd"];
            [self.saleTableView reloadData];
            [self.saleTableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(self.saleArray.count * 200);
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

- (void) loadCategory {
    CACategoryApi *categoryApi = [[CACategoryApi alloc] init];
    [categoryApi startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        CACategoryApi *api = (CACategoryApi *) request;
        if (api.done) {
            self.categoryArray = api.responseObject[@"result"];
            [self.cateTableView reloadData];
            
            [self.cateTableView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(self.categoryArray.count * 150);
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:api.errorMsg];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        [SVProgressHUD lm_displayErrorWithStatus:@"请求出错"];
    }];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 1) {
        return _saleArray.count;
    } else if (tableView.tag == 2) {
        return _categoryArray.count;
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1) {
        CASaleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:saleIdentifier forIndexPath:indexPath];
        NSDictionary *dict = _saleArray[indexPath.row];
        NSString *imageUrl = [NSString stringWithFormat:@"%@%@", BASE_IMAGE_DOMAIN, dict[@"pic_path"]];
        [cell.saleImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else if (tableView.tag == 2) {
        CACategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cateIdentifier forIndexPath:indexPath];
        NSDictionary *dict = _categoryArray[indexPath.row];
        
        NSString *imageUrl = [NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, dict[@"img"]];
        [cell.cateImageView sd_setImageWithURL:[NSURL URLWithString:imageUrl]];
        cell.titleLabel.text = dict[@"name"];
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else {
        return  nil;
    }
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1) {
        return 200;
    } else if (tableView.tag ==2) {
        return 150;
    } else {
        return 0;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView.tag == 1) {
//        NSDictionary *dict = self.categoryArray[indexPath.row];
//        CAGoodsListViewController *goodsListVC = [CAGoodsListViewController new];
//        goodsListVC.vcTitle = dict[@"ad_name"];
//        goodsListVC.category = @"";
//        goodsListVC.isYPH = @"0";
//        goodsListVC.isVip = @"0";
//        goodsListVC.isSecond = @"1";
//        goodsListVC.goodsName = @"";
//        [self.navigationController pushViewController:goodsListVC animated:YES];
    } else if (tableView.tag == 2) {
        NSDictionary *dict = self.categoryArray[indexPath.row];
        CAGoodsListViewController *goodsListVC = [CAGoodsListViewController new];
        goodsListVC.vcTitle = dict[@"name"];
        goodsListVC.category = [NSString stringWithFormat:@"%ld", [dict[@"id"] integerValue]];
        goodsListVC.isYPH = @"0";
        goodsListVC.isVip = @"0";
        goodsListVC.isSecond = @"0";
        goodsListVC.goodsName = @"";
        [self.navigationController pushViewController:goodsListVC animated:YES];
    }
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"%ld", index);
}


@end
